<template>
  <div id="app">
    <img src="./assets/logo.png">
    <input type="button"  value="访客连接socket" @click="visitorSocketInit">
    <input type="button"  value="访客端拉取历史消息" @click="vHisMsgLists">
    <input type="button"  value="访客端已读消息最后时间" @click="vLastTimes">
    <input type="button"  value="客服连接socket" @click="serverSocketInit">
    <input type="button"  value="客服端拉取列表" @click="sessionLists">
    <input type="button"  value="客服端历史消息" @click="sHisMsgLists">
    <input type="button"  value="客服端已读消息最后时间" @click="sLastTimes">
    <input type="button"  value="客服转移访客" @click="transferVisitors">
    <input type="button"  value="客服主动退出" @click="serverQuits">
    <input type="button"  value="客服端第一条消息" @click="firstMsgs">

    <div/>
    <input type="text" :value="webSocketUrl"> 
    客服id<input type="text" v-model="serverId">
  </div>
</template>

<script>
  

  
  //访客心跳
  var visitorHearBeat={
      type:2
  }

  //客服心跳
  var serverHeartBeat={
      type:6
  }


export default {
  name: 'App',
  data(){
        return {
          websocket:null,
          webSocketUrl:"ws://localhost:8099/",//webSocket 服务器地址
          webSocketPingTimer:null,//心跳定时器
          webSocketIsOpen:false,  //webSocket是否打开
          webSocketPingTime:10000,// 心跳的间隔，当前为 10秒
          webSocketReconnectCount: 0,//重连次数
          webSocketIsReconnect: true, // 是否重连,
          // 尝试重新连接的最大次数
          webSocketReconnectMaxCount: 5,
          //是否访客
          isVisitor:false,
          //客服id
          serverId:1,
        }
    },
	methods:{
        //访客登录
        visitorLog(){
            //访客登录请求
            var visitorLogin={
                    //访客编号
                    visitorCode:'103FK006',
                    //是否断线重连
                    isOffLineLogin:false
            }

            //访客登录
            var  p={
                //0代表访客登录
                type:0,
                data:JSON.stringify(visitorLogin)
            }
            this.webSocket.send(JSON.stringify(p));
        },

        //访客端已读消息最后时间
        vLastTimes(){
            //访客端已读消息最后时间
            let a={
                //最后已读消息时间戳
                lastReadTime:1572764859522
            };

            let dat={
                //3 代表访客端已读消息最后时间
                type:3,
                data:JSON.stringify(a)
            };
            this.webSocket.send(JSON.stringify(dat));
        },

        //客服已读消息最后的时间
        sLastTimes(){
            let a={
                //客服已读消息最后的时间戳
                lastReadTime:1572764859522,
                //读的是哪个访客的消息
                visitorId:36
            };
            let dat={
                //7代表客服已读消息最后的时间
                type:7,
                data:JSON.stringify(a)
            };
            this.webSocket.send(JSON.stringify(dat));
        },

        //客服登录
        serverLog(){
            var that=this;
            //客服登录请求
            var serverLogin={
                //客服id
                serverId:that.serverId,
                //是否断线重连
                isOffLineLogin:false,
                //一个标记用来标记浏览器聊天tab页是否应该关闭
                tag:"123",
                //公司id
                companyId:1
            }
  
            //客服登录
            var serverP={
                //1代表客服登录
                type:1,
                data:JSON.stringify(serverLogin)
            }

            this.webSocket.send(JSON.stringify(serverP));
        },

        //客服端会话列表
        sessionLists(){
            let data={
                //5 代表查询左侧的聊天列表
                type:5
            };
            this.webSocket.send(JSON.stringify(data));
        },

        //访客端历史消息
        vHisMsgLists(){
            let a={
                //一次查询的数量限制
                limit:10,
                //是否按照消息时间升序，false代表降序
                asc:false,
                //某个时间以上的消息
                //time:
            };
            let dat={
                //4 代表访客拉取历史消息
                type:4,
                data:JSON.stringify(a)
            };
            this.webSocket.send(JSON.stringify(dat));
        },

        //客服历史消息
        sHisMsgLists(){
            let a={
                //一次拉取数量限制
                limit:10,
                //是否按照消息时间升序，false代表降序
                asc:false,
                //访客id
                visitorId:36
            };
            let dat={type:8,data:JSON.stringify(a)};
            this.webSocket.send(JSON.stringify(dat));
        },

       //客服主动转移访客
       transferVisitors(){
           let a={
               //转移给客服的id
               toServerId:2,
               //访客id
               visitorId:36,
               //访客云信账号
               visitorAccid:"c6f0832d6ad44106ad997424f88c2bbf"
           };
           let dat={
               //9代表客服主动转移访客请求
               type:9,
               data:JSON.stringify(a)
            };
           this.webSocket.send(JSON.stringify(dat));
       },

       //客服主动关闭tab页或浏览器
       serverQuits(){
           
          let dat={type:10};
          this.webSocket.send(JSON.stringify(dat));
       },

         //客服端第一条消息，需要通知访客连接网易云信
        firstMsgs(){
            let a={
                //访客id
                visitorId:36,
                //发送的消息
                lastMsg:"你好"
            };
            let dat={type:11,data:JSON.stringify(a)};
             this.webSocket.send(JSON.stringify(dat));
        },


        //访客建立webSocket连接
        visitorSocketInit(){
            this.isVisitor=true;
            // 修改是否重连为 true
            this.webSocketIsReconnect = true;
            this.webSocket = new WebSocket(this.webSocketUrl+"");
            this.webSocket.onopen = this.webSocketHandleOpen;
            this.webSocket.onerror = this.webSocketHandleError;
            this.webSocket.onmessage = this.webSocketHandleMessage;
            this.webSocket.onclose = this.webSocketHandleClose;
        },

      
        //客服建立webSocket连接
        serverSocketInit(){
            this.isVisitor=false;
            // 修改是否重连为 true
            this.webSocketIsReconnect = true;
            this.webSocket = new WebSocket(this.webSocketUrl+"");
            this.webSocket.onopen = this.webSocketHandleOpen;
            this.webSocket.onerror = this.webSocketHandleError;
            this.webSocket.onmessage = this.webSocketHandleMessage;
            this.webSocket.onclose = this.webSocketHandleClose;
        },

        // WebSocket 重连
        webSocketReconnect() {
            if (this.webSocketIsOpen) {
                return false;
            }
            this.webSocketReconnectCount += 1;
            // 判断是否到了最大重连次数
            if (
                this.webSocketReconnectCount >= this.webSocketReconnectMaxCount
            ) {
                this.webSocketWarningText = "重连次数超限";
                return false;
            }
            if(this.isVisitor){
                // 初始化
                this.visitorSocketInit();
            }else{

                this.serverSocketInit();
            }
            

            // 每过 5 秒尝试一次，检查是否连接成功，直到超过最大重连次数
            let timer = setTimeout(() => {
                this.webSocketReconnect();
                clearTimeout(timer);
            }, 5000);
        },

        // 定时心跳
        webSocketPing() {
            var that=this;
            this.webSocketPingTimer = setTimeout(() => {
                if (!this.webSocketIsOpen) {
                    return false;
                }
                console.log("心跳");
                const payload = {
                    type: 0
                };
                //访客心跳
                if(that.isVisitor){
                    this.webSocketSend(visitorHearBeat);
                }else{
                    this.webSocketSend(serverHeartBeat);
                }
                clearTimeout(this.webSocketPingTimer);
                // 重新执行
                this.webSocketPing();
            }, this.webSocketPingTime);
        },

        // 发送ws消息
        webSocketSend(payload) {
            console.log("socket 发送的数据为",payload);
            this.webSocket.send(JSON.stringify(payload));
        },
         // WebSocket 打开成功后
        webSocketHandleOpen() {
            console.log("连接打开");
            this.webSocketIsOpen = true;
             // 清空重连的次数
            this.webSocketReconnectCount = 0;
            if(this.isVisitor){
                //发送访客登录信息
                this.visitorLog();
            }else{
                //发送客服登录信息
                this.serverLog();
            }
            // 开启定时心跳
            this.webSocketPing();
        },
        // WebSocket 关闭
        webSocketHandleClose() {
            console.log("连接断开");
            // 关闭心跳
            this.webSocketClose();
        },
         // 断开连接时
        webSocketClose() {
            // 修改状态为未连接
            this.webSocketIsOpen = false;
            this.webSocket = null;
            // 判断是否重连
            if (
                this.webSocketIsReconnect &&
                this.webSocketReconnectCount === 0
            ) {
                // 第一次直接尝试重连
                this.webSocketReconnect();
            }
        },
        // WebSocket 发生错误时
        webSocketHandleError(err) {
            console.log("连接报错：", err);
            // 关闭心跳
            this.webSocketClose();
        },
        // 接收到消息时
        webSocketHandleMessage(event) {
            // 响应体的message
            const data = event.data;
            console.log("客服端接收到的消息为:",data);
           
        }
    },
    mounted(){
        
    },
    created(){
       //this.webSocketInit()
    }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
